package com.caiyigo.baihua.fetion.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

import org.hibernate.Session;
import org.hibernate.transform.Transformers;

import com.caiyigo.baihua.entity.CjBean;
import com.caiyigo.baihua.entity.Xuesheng;
import com.caiyigo.baihua.fetion.HibernateSessionFactory;
import com.caiyigo.baihua.fetion.Result;

public class DbDaoImpl implements DbDao {

	public DbDaoImpl() {
		super();
	}

	@Override
	public Map<String, String> getZdyList(String serviceId,
			String appendMessage, List<Xuesheng> xueshengsList) {
		Map<String, String> xueshengMap = new HashMap<String, String>();
		for (Xuesheng xuesheng : xueshengsList) {
			xueshengMap.put(xuesheng.getXsSjOne(), appendMessage);
		}
		return xueshengMap;
	}

	@Override
	public Map<String, String> getZwList(String pici, String serviceId,
			String appendMessage, Map<String, Xuesheng> xueshengMapKeyAtZkz) {
		Map<String, String> map = new HashMap<String, String>();
		Session session = HibernateSessionFactory.getSession();
		@SuppressWarnings("unchecked")
		List<CjBean> kaoshiZws = session
				.createSQLQuery(
						"SELECT   zkz, GROUP_CONCAT( '[科目:',  kemu,  ',考试时间：',  shijian, ',考场:',   kaochang,',地址:',  dizhi,    ',试室:',   shishi, ',座位号:', zuoweihao, ',答题卡:', datika, ']') message FROM kaoshizw t, xuesheng b WHERE t.xsid = b.id  AND pici = :pici AND issend NOT IN ('1') AND sshm = :ks_xs_sshm GROUP BY t.xsid")
				.setResultTransformer(Transformers.aliasToBean(CjBean.class))
				.setString("pici", pici).setString("ks_xs_sshm", serviceId)
				.list();
		if (!kaoshiZws.isEmpty()) {
			for (Iterator<CjBean> iterator = kaoshiZws.iterator(); iterator
					.hasNext();) {
				CjBean kaoshizw = (CjBean) iterator.next();
				Xuesheng xuesheng = xueshengMapKeyAtZkz.get(kaoshizw
						.getZkz());
				if (null != xuesheng) {
					map.put(xuesheng.getXsSjOne(),
							"姓名:" + xuesheng.getXsXm() + ",准考证："
									+ xuesheng.getXsZkz() + ","
									+ kaoshizw.getMessage() + appendMessage);
				}

			}
		}
		return map;
	}

	@Override
	public Map<String, String> getCjList(String pici, String serviceId,
			String appendMessage, Map<String, Xuesheng> xueshengMapKeyAtZkz) {
		Map<String, String> map = new HashMap<String, String>();
		final Session session = HibernateSessionFactory.getSession();
		@SuppressWarnings("unchecked")
		List<CjBean> kaoshiZws = session
				.createSQLQuery(
						"SELECT zkz, GROUP_CONCAT( '[科目代码:',  kmid,',科目名称：',(SELECT  kmmc FROM kaoshikemu  WHERE kmdm = kmid), ',分数:',cjfs,']' ) message FROM kaoshicj t, xuesheng b WHERE t.xsid = b.id AND t.cjfs IS NOT NULL AND pici = :pici AND issend NOT IN ('1') AND sshm = :ks_xs_sshm GROUP BY t.xsid ")
				.setResultTransformer(Transformers.aliasToBean(CjBean.class))
				.setString("pici", pici).setString("ks_xs_sshm", serviceId)
				.list();
		if (!kaoshiZws.isEmpty()) {
			for (Iterator<CjBean> iterator = kaoshiZws.iterator(); iterator
					.hasNext();) {
				CjBean kaoshizw = (CjBean) iterator.next();
				Xuesheng xuesheng = xueshengMapKeyAtZkz.get(kaoshizw
						.getZkz());
				if (null != xuesheng) {
					map.put(xuesheng.getXsSjOne(),
							"姓名:" + xuesheng.getXsXm() + ",准考证："
									+ xuesheng.getXsZkz() + ","
									+ kaoshizw.getMessage() + appendMessage);
				}

			}
		}
		return map;
	}

	public void updateSend(List<Future<Result>> resultList, boolean isZw,
			String pici,Map<String, Xuesheng>map) throws Exception {
		final Session session = HibernateSessionFactory.getSession();
		try {
			String updateSql;
			if (isZw) {
				updateSql = "UPDATE kaoshizw SET isSend=?,isSendReason=? WHERE xsid=? AND pici=?";
			} else {

				updateSql = "UPDATE kaoshicj SET isSend=?,isSendReason=? WHERE xsid=? AND pici=?";
			}

			Connection conn = session.connection();
			PreparedStatement stmt = conn.prepareStatement(updateSql);
			conn.setAutoCommit(false);
			int b = 0;
			for (Iterator<Future<Result>> iterator = resultList.iterator(); iterator
					.hasNext();) {
				Result future = iterator.next().get();
				if (null == future) {
					continue;
				}
				b++;
				if (future.getResult().equals("1")
						|| future.getResult().equals("2")) {
					stmt.setString(1, "1");
				} else {
					stmt.setString(1, "-1");
				}
				stmt.setString(2, future.getResult());
				stmt.setInt(3, map.get(future.getZkz()).getId());
				stmt.setString(4, pici);
				stmt.addBatch();
				if (b % 100 == 0) {
					stmt.executeBatch();
					conn.commit();
				}
			}
			stmt.executeBatch();
			conn.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	public List<Xuesheng> getXueshengsListFromDataBase(String serviceId) {
		final Session session = HibernateSessionFactory.getSession();
		List<Xuesheng> xueshengs = session
				.createQuery(
						"FROM Xuesheng WHERE  sshm=:sshm AND xsSjOne IS NOT NULL")
				.setString("sshm", serviceId).list();
		session.close();
		return xueshengs;
	}

}
